﻿<script lang="ts" setup>
import { Ref } from 'vue'
import VditorPreview from 'vditor/dist/method.min'
import { onMountedOrActivated } from '@/hooks/onMountedOrActivated'
import { storeToRefs } from 'pinia'
import { useSystemConfigStore } from '@/store/storage/systemConfigStore'
import { loadEnv } from '^/index'
const systemConfigStore = useSystemConfigStore()
const { systemConfig } = storeToRefs(systemConfigStore)
const { VITE_PUBLIC_PATH } = loadEnv()

const viewerRef = ref<ElRef>(null)
const vditorPreviewRef = ref(null) as Ref<Nullable<VditorPreview>>
const props = defineProps({
  value: { type: String },
  class: { type: String }
})
const getTheme = (
  isLight: boolean,
  themeMode: 'default' | 'content' | 'code' = 'default'
) => {
  const isDark = !isLight
  switch (themeMode) {
    case 'default':
      return isDark ? 'dark' : 'classic'
    case 'content':
      return isDark ? 'dark' : 'light'
    case 'code':
      return isDark ? 'dracula' : 'github'
  }
}
const initVditor = () => {
  const viewerEl = unref(viewerRef) as HTMLElement
  vditorPreviewRef.value = VditorPreview.preview(viewerEl, props.value, {
    cdn: VITE_PUBLIC_PATH + 'vditor',
    mode: getTheme(systemConfig.value.isLight, 'content'),
    theme: {
      // 设置内容主题
      current: getTheme(systemConfig.value.isLight, 'content')
    },
    hljs: {
      // 设置代码块主题
      style: getTheme(systemConfig.value.isLight, 'code')
    }
  })
}
watch(
  () => systemConfig.value.isLight,
  (val) => {
    VditorPreview.setContentTheme(getTheme(val, 'content'))
    VditorPreview.setCodeTheme(getTheme(val, 'code'))
    initVditor()
  }
)

watch(
  () => props.value,
  (v, oldValue) => {
    v !== oldValue && initVditor()
  }
)

function destroy() {
  const vditorInstance = unref(vditorPreviewRef)
  if (!vditorInstance) return
  try {
    vditorInstance?.destroy?.()
  } catch (error) {
    console.log(error)
  }
  vditorPreviewRef.value = null
}

onMountedOrActivated(initVditor)

onBeforeUnmount(destroy)
onDeactivated(destroy)
</script>

<template>
  <div ref="viewerRef" id="markdownViewer" :class="$props.class"></div>
</template>
